package com.kakavr.user.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.kakavr.auth.util.EncryptionUtils;
import com.kakavr.base.controller.BaseController;
import com.kakavr.base.exception.ValidateParamException;
import com.kakavr.pay.constant.WxConstant;
import com.kakavr.pay.util.HttpClientUtil;
import com.kakavr.pay.util.WXPayUtil;
import com.kakavr.result.MsgResult;
import com.kakavr.result.constant.MsgConstants;
import com.kakavr.user.service.IUserService;
import  com.kakavr.order.service.IPurchaseHistoryService;
import com.kakavr.util.SessionUtils;
import com.kakavr.util.ValidatorUtils;
import com.kakavr.shop.service.ITradeFlowService;
/**
 * 玩家登录
 * @author gang.yang
 *
 */
@RestController
@RequestMapping("/n/userLogin")
public class UserLoginController extends BaseController {
	@Resource
	private IUserService userService;
	
	@Resource
	private IPurchaseHistoryService purchaseHistoryService;
	
	@Resource
	private ITradeFlowService tradeFlowService;
	
	private static Map<String,Map<String,Object>>  session = Maps.newHashMap();
	

	/**
	 * 用户名密码登录
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "signIn", method = RequestMethod.POST)
	public Map<String, Object> signIn(HttpServletRequest request) {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		SessionUtils.set("redirectPage", "es");
		if (StringUtils.isBlank(userName)) {
			throw new ValidateParamException(MsgConstants.MSG_CODE_1001,
					MsgConstants.MSG_CONTENT_1001, "用户名");
		}
		if (StringUtils.isBlank(password)) {
			throw new ValidateParamException(MsgConstants.MSG_CODE_1001,
					MsgConstants.MSG_CONTENT_1001, "密码");
		}
		Map<String, Object> map = Maps.newHashMap();
		map.put("username", userName);
		Map<String, Object> user = userService.getUserInfo(map);
		if (null == user || user.isEmpty()) {
			throw new ValidateParamException(MsgConstants.MSG_CODE_1002,
					MsgConstants.MSG_CONTENT_1002, "用户名密码");
		}
		Object pass = user.get("password");
		info("+++++++++++++用户密码登录："+JSON.toJSONString(user));
		if (EncryptionUtils.md5(password).equals(pass)) {
			SessionUtils.setCurUser(user);
			map.clear();
			map.put("userId", user.get("id"));
			map.put("name", user.get("name"));
			map.put("userName", userName);
			map.put("times", user.get("times"));
			map.put("sessionId", SessionUtils.getSession().getId());
			//以下获取评价ID
			String rediectPage=String.valueOf(SessionUtils.get("redirectPage"));
			Map<String,Object> usermap=new HashMap<String,Object>();
			usermap.put("userId", user.get("id"));
			usermap=purchaseHistoryService.selectNowPurchaseHistoryId(usermap);
			if(null!=usermap){
				map.put("purchaseId", usermap.get("id"));
			}else{
				map.put("purchaseId", "");
			}
			info(JSON.toJSONString(SessionUtils.get("redirectPage")));
			return MsgResult.okResultData(map);
		}
		throw new ValidateParamException(MsgConstants.MSG_CODE_1002,
				MsgConstants.MSG_CONTENT_1002, "用户名密码");
	}

	/**
	 * 返回微信授权地址（用于公众号内登录）
	 */
	@RequestMapping(value = "getMobileLoginCode", method = RequestMethod.GET)
	public Map<String, Object> getMobileLoginCode(HttpServletRequest request) {
		info("+++++++++++微信授权登录日志参数："+request.getParameter("redirectPage"));
		SessionUtils.set("redirectPage", request.getParameter("redirectPage"));
		return MsgResult.okResultData(WxConstant.getOAuthUrl(WxConstant
				.getUserMobileRedirectUri()));
	}
	
	/**
	 * 微信授权确认登录后返回页面
	 */
	@RequestMapping(value = "signInByWxMobile", method = RequestMethod.GET)
	public ModelAndView signInByWxMobile(HttpServletRequest request) {
		String state = request.getParameter("state");
		String code = request.getParameter("code");
		String redirectPage = request.getParameter("redirectPage");
		info("+++++++++++++微信授权登录回调："+JSON.toJSONString(redirectPage));
		if (!WxConstant.LOGIN_STATE.equals(state)) {
			return new ModelAndView("redirect:/player/index.html");
		}
		if (StringUtils.isBlank(code)) {
			return new ModelAndView("redirect:/player/index.html");
		}
		String accessTokenUrl = WxConstant.getAccessTokenUrl(code);
		Map<String, Object> map = HttpClientUtil.doGet(accessTokenUrl);
		info("微信授权登录后返回map的值：" + map);
		// 取用户信息
		Map<String, Object> user = HttpClientUtil.doGet(WxConstant
				.getUserInfoUrl(map.get("access_token"), map.get("openid")));
		user.put("storeId", SessionUtils.getShopId());
		info("微信授权登录后返回用户信息的值：" + user);
		Map<String, Object> userInfo = userService.getUserInfo(user);
		if(null != userInfo && !userInfo.isEmpty()){
			userInfo.put("name", user.get("nickname"));
			userInfo.put("headImg", user.get("headimgurl"));
			try {
				userService.updateUser(userInfo);
			} catch (Exception e) {
			}
		}else{
			try{
				userService.addUser(user);
			}catch(Exception e){
				user.put("nickname", "卡卡玩家");
				userService.addUser(user);
			}
			userInfo = userService.getUserInfo(user);
		}
		info("+++++++++++++微信手机登录："+JSON.toJSONString(userInfo));
		SessionUtils.setCurUser(userInfo);
		Map<String,Object> usermap=new HashMap<String,Object>();
		userInfo.put("userId", userInfo.get("id"));
		info("请求评论ID的参数："+JSON.toJSONString(userInfo));
		usermap=purchaseHistoryService.selectNowPurchaseHistoryId(userInfo);
		info("+++++++++++++查看参数中的redirectPage值："+redirectPage+usermap);
		if("yes".equals(redirectPage)&&null!=usermap){
			info("rediectPage参数为yes跳转吐槽："+JSON.toJSONString(userInfo));
			return new ModelAndView("redirect:/player/evaluate.html?purchaseId="+String.valueOf(usermap.get("id")));//跳转吐槽页面
		}
		return new ModelAndView("redirect:/player/home.html");
	}
	
	/**
	 * 返回扫码地址（用于页面生成二维码）
	 */
	@RequestMapping(value = "getLoginCode", method = RequestMethod.GET)
	public Map<String, Object> getLoginCode(HttpServletRequest request) {
		String sessionId = WXPayUtil.generateUUID();
		String url  = WxConstant.getOAuthUrl(WxConstant
				.getUserRedirectUri(sessionId));
		Map<String,Object> map = Maps.newHashMap();
		map.put("codeUrl", url);
		map.put("sessionId", sessionId);
		return MsgResult.okResultData(map);
	}

	/**
	 * 确认登录后返回页面
	 */
	@RequestMapping(value = "signInByWx", method = RequestMethod.GET)
	public ModelAndView signInByWx(HttpServletRequest request) {
		String state = request.getParameter("state");
		String code = request.getParameter("code");
		String sessionId = request.getParameter("sessionId");
		if (!WxConstant.LOGIN_STATE.equals(state)) {
			return new ModelAndView("redirect:/mach/login.html");
		}
		if (StringUtils.isBlank(code)) {
			return new ModelAndView("redirect:/mach/login.html");
		}
		String accessTokenUrl = WxConstant.getAccessTokenUrl(code);
		Map<String, Object> map = HttpClientUtil.doGet(accessTokenUrl);
		info("微信授权登录后返回map的值：" + map);
		// 取用户信息
		Map<String, Object> user = HttpClientUtil.doGet(WxConstant
				.getUserInfoUrl(map.get("access_token"), map.get("openid")));
		info("微信授权登录后返回用户信息的值：" + map);
		Map<String, Object> userInfo = userService.getUserBywxid(user);
		if(null != userInfo && !userInfo.isEmpty()){
			userInfo.put("name", user.get("nickname"));
			userInfo.put("headImg", user.get("headimgurl"));
			try {
				userService.updateUser(userInfo);
			} catch (Exception e) {
			}
		}else{
			try{
				info("+++++++++++++微信登录："+JSON.toJSONString(user));
				userService.addUser(user);
			}catch(Exception e){
				user.put("nickname", "卡卡玩家");
				userService.addUser(user);
			}
			userInfo = userService.getUserInfo(user);
		}
		session.put(sessionId, userInfo);
		return new ModelAndView("redirect:/mach/success.html");
	}

	/**
	 * 注册
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "register", method = RequestMethod.POST)
	public Map<String, Object> register(HttpServletRequest request) {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String num = request.getParameter("num");
		String money = request.getParameter("money");
		String storeId = request.getParameter("storeId");
		if (StringUtils.isBlank(userName)) {
			throw new ValidateParamException(MsgConstants.MSG_CODE_1001,
					MsgConstants.MSG_CONTENT_1001, "用户名");
		}
		if (!ValidatorUtils.isPass(password)) {
			throw new ValidateParamException(MsgConstants.MSG_CODE_2004,
					MsgConstants.MSG_CONTENT_2004, "密码");
		}
		
		Map<String, Object> map = Maps.newHashMap();
		map.put("username", userName);
		Map<String,Object> usermap=userService.getUserInfo(map);
		if(null!=usermap){
			
			throw new ValidateParamException(MsgConstants.MSG_CODE_2008,
					MsgConstants.MSG_CONTENT_2008, "用户名");
		}
		map.put("storeId", storeId);
		map.put("times", 0);
		map.put("isActivity", 0);
		map.put("password", EncryptionUtils.md5(password));
		if(StringUtils.isNotEmpty(num)&&StringUtils.isNotEmpty(money)){
			map.put("times", num);
			map.put("amount", money);
			map.put("isActivity", 1);
		}
		Long userId = SessionUtils.getUserId();
		if (null == userId) {
			userService.addUserByRegister(map);
			SessionUtils.setCurUser(map);
		} else {
			if (null == SessionUtils.getCurUser().get("isMaster")) {
				map.put("id", userId);
				userService.updateUser(map);
			}
		}
		return MsgResult.okResult();
	}

	/**
	 * 是否 已经登录
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "isLogin", method = RequestMethod.GET)
	public Map<String, Object> isLogin(HttpServletRequest request) {
		String sessionId = request.getParameter("sessionId");
		Map<String, Object> result = Maps.newHashMap();
		if(StringUtils.isBlank(sessionId)){
			result.put("isLogin", 0);
			return MsgResult.okResultData(result);
		}
		Map<String,Object> user = session.get(sessionId);
		if (null == user || user.isEmpty()) {
			result.put("isLogin", 0);
			return MsgResult.okResultData(result);
		}
		SessionUtils.setCurUser(user);
		result.put("isLogin", 1);
		result.put("userId", user.get("id"));
		result.put("name", user.get("name"));
		result.put("userName", user.get("username"));
		result.put("times", user.get("times"));
		result.put("sessionId", SessionUtils.getSession().getId());
		session.remove(sessionId);
		return MsgResult.okResultData(result);
	}

	/**
	 * 退出登录
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "logon", method = RequestMethod.GET)
	public Map<String, Object> logon(HttpServletRequest request) {
		HttpSession session = SessionUtils.getSession();
		if (null != session) {
			session.invalidate();
		}
		return MsgResult.okResult();
	}

}
